﻿using Barcode_Project.Entity;
using Barcode_Project.InitPrint;
using Barcode_Project.Local;
using Barcode_Project.Network;
using DevExpress.AspNetCore.Reporting.WebDocumentViewer.Native.DataContracts;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.POIFS.Storage;
using NPOI.SS.Formula.Functions;
using RJCP.IO.Ports;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Utils.Drawing.Helpers.NativeMethods;
using static System.Net.WebRequestMethods;
using Match = System.Text.RegularExpressions.Match;

namespace Barcode_Project.ProBarPrint
{
    public partial class PlanPrint : DevExpress.XtraEditors.XtraForm
    {
        Dictionary<string, string> datas;
        HttpAgreement http;
        public PlanPrint(Dictionary<string, string> pars)
        {
            InitializeComponent();
            datas = pars;
        }
        private void PlanPrint_Load(object sender, EventArgs e)
        {
            try
            {
                http = new HttpAgreement();
                new ComputerTask().LoadPrinter(select_printer);
                new ComputerTask().LoadTemplate(select_template);
                new ComputerTask().LoadMachine(select_machine);
                OpenPort();

                CommonMethods.SetFormValue(this.group_data.Controls, datas, "input_");

                // 判断是否最后一道工序
                // 如果是最后一道工序，将执行标准带出来
                if (IsFinalStep())
                {
                    // 显示执行标准
                    var zhxbz = getZhxbz();
                    input_zhxbz.EditValue = zhxbz;
                    // 显示材质
                    var cuCaiZhi = getCuCaiZhi();
                    input_cu_material.EditValue = cuCaiZhi;
                }
                input_produce_proName.EditValue = "[请选择生产存货]";

                if (IsFinalStep())
                {
                    //默认是计划的成品
                    datas["proCode"] = datas["proCode"].ToString();
                    datas["proName"] = datas["proName"].ToString();
                    datas["spec"] = datas["spec"].ToString();
                    datas["unitName"] = datas["unitName"].ToString();
                    input_produce_proName.EditValue = datas["proName"].ToString();
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(datas["cu_bcp"].ToString()))
                    {
                        //默认是计划的半成品
                        datas["proCode"] = datas["cu_bcp"].ToString();
                        datas["proName"] = datas["produce_proName"].ToString();
                        datas["spec"] = datas["produce_spec"].ToString();
                        datas["unitName"] = datas["produce_unitName"].ToString();

                        input_produce_proName.EditValue = datas["produce_proName"].ToString();
                    }
                }
                if (datas["gxCode"] == "ZD")
                {
                    labelControl23.Text = "实际个数";
                }
                this.GetGYPrintData();

                la_unitName.Text = datas["unitName"].ToString();//计量单位
                input_cu_inspector.EditValue = "[请选择检验人员]";
                LoadPrintedBarCodes();
                SetCheckValue();

                input_happenDate.EditValue = DateTime.Now.ToString("yyyy-MM-dd");
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        // 判断是否最后一道工序
        bool IsFinalStep()
        {
            var gxCode = datas["gxCode"];
            var plCode = datas["plCode"];

            var queryDic = new Dictionary<string, string>();
            queryDic["gxCode"] = gxCode;
            queryDic["plCode"] = plCode;

            string url = CommonMethods.APIUrl() + "IsFinalStep";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(queryDic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                return bool.Parse(obj["data"].ToString());
            }

            return false;
        }
        // 获取执行标准
        string getZhxbz()
        {
            var plCode = datas["plCode"];
            var queryDic = new Dictionary<string, string>();
            queryDic["plCode"] = plCode;

            string url = CommonMethods.APIUrl() + "getZhxbz";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(queryDic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return "";
            }
            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                return obj["data"].ToString();
            }

            return "";

        }
        string gyPrintData = "";
        // 获取计划的材质自定义字段
        /// <summary>
        /// 获取关联工序工艺打印字段值
        /// </summary>
        private void GetGYPrintData()
        {

            var queryDic = new Dictionary<string, string>();
            queryDic["plCode"] = datas["plCode"];
            queryDic["gxCode"] = datas["gxCode"];
            string url = CommonMethods.APIUrl() + "GetPrintGYData";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(queryDic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                gyPrintData = obj["data"].ToString();
            }
        }
        string getCuCaiZhi()
        {
            var plCode = datas["plCode"];
            var queryDic = new Dictionary<string, string>();
            queryDic["plCode"] = plCode;

            string url = CommonMethods.APIUrl() + "getCuCaiZhi";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(queryDic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return "";
            }
            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                return obj["data"].ToString();
            }

            return "";
        }
        // 设置需检验下拉框的值
        void SetCheckValue()
        {
            DataTable table = new DataTable();
            table.Columns.Add("value");
            table.Columns.Add("name");
            var r = table.NewRow();
            r["value"] = "1";
            r["name"] = "是";
            table.Rows.Add(r);
            r = table.NewRow();
            r["value"] = "0";
            r["name"] = "否";
            table.Rows.Add(r);

            cb_isCheck.DataSource = table;
            cb_isCheck.DisplayMember = "name"; // 显示的列名
            cb_isCheck.ValueMember = "value";

            //// 如果是复合工序，默认为是
            //if (datas["gxCode"] == "FH")
            //{
            //    cb_isCheck.SelectedValue = 1;
            //}
            //else
            //{
            //    cb_isCheck.SelectedIndex = 0;
            //}
            cb_isCheck.SelectedIndex = 1;
        }

        SerialPortStream _port;
        void OpenPort()
        {
            try
            {
                var comName = ConfigurationManager.AppSettings["COM"].ToString();
                var baudRate = ConfigurationManager.AppSettings["baud rate"].ToString();

                if (_port == null)
                {
                    _port = new SerialPortStream(comName, int.Parse(baudRate));
                    _port.DataReceived += _port_DataReceived;

                    _port.Open();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void _port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    var existStr = _port.ReadExisting();
                    string result = ConvertToNumericString(existStr);
                    //wn00000.14kg
                    led_weight.Value = result;
                    input_proWeight.Text = result;
                }));
            }
            catch (Exception ex)
            {

            }
        }
        static string lastValidNumber = string.Empty;  // 用于存储最后一个有效的数字
        static string ConvertToNumericString(string input)
        {
            // 使用正则表达式提取数字部分
            string pattern = @"\d*\.\d+";
            Match match = Regex.Match(input, pattern);

            if (match.Success)
            {
                string numericString = match.Value;

                // 使用浮点数解析和格式化来去除多余的前导0
                decimal number = decimal.Parse(numericString);
                lastValidNumber = number.ToString("0.##");  // 更新上一次有效数字
                return lastValidNumber;
            }

            // 如果没有找到有效数字，返回上一次有效数字
            return lastValidNumber;
        }
        // 加载该计划，该工序下所有已打印条码
        void LoadPrintedBarCodes()
        {

            var list = new RemoteRequest()
                .GetPrintedBarCodes_ByPlCode_GxCode(datas["plCode"], datas["gxCode"]);

            gridControl_printedBarcodes.DataSource = list;
            gridControl_printedBarcodes.RefreshDataSource();
        }


        private void button_viewCrafts_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var url = "";
            var craft = datas["gxCode"];

            switch (craft)
            {
                case "YS":
                    url = $@"Plan/YinShuaForm?plCode={datas["plCode"]}&isRead=0";
                    break;
                case "FH":
                    url = $@"Plan/FuHeForm?plCode={datas["plCode"]}&isRead=0";
                    break;
                case "GSFH":
                    url = $@"Plan/GSFuHeForm?plCode={datas["plCode"]}&isRead=0";
                    break;
                case "WRJFH":
                    url = $@"Plan/WRJFuHeForm?plCode={datas["plCode"]}&isRead=0";
                    break;
                case "FQ":
                    url = $@"Plan/FenQieForm?plCode={datas["plCode"]}&isRead=0";
                    break;
                case "CPFQ":
                    url = $@"Plan/CPFenQieForm?plCode={datas["plCode"]}&isRead=0";
                    break;
                case "FQ1":
                    url = $@"Plan/FenQie1Form?plCode={datas["plCode"]}&isRead=0";
                    break;
                case "ZD":
                    url = $@"Plan/ZhiDaiForm?plCode={datas["plCode"]}&isRead=0";
                    break;
                default:
                    break;
            }

            new RemoteRequest().OpenWebPage(url);
        }

        List<UsedBarCode> outputBarCodes { get; set; }

        Dictionary<string, object> d_dic = new Dictionary<string, object>();
        private void button_print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {

                if (!this.button_print.Enabled)
                {
                    return;
                }

                this.button_print.Enabled = false;

                var nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                // 聚焦到已打印条码上，避免用户输入数字直接按回车时，无法读取数据
                gridControl_printedBarcodes.Focus();

                if (!this.CheckBeforePrint())
                {
                    this.button_print.Enabled = true;
                    return;
                }
                CommonMethods.SetParameterValue(ref datas, this.group_data.Controls, "input_");
                d_dic["proWeight"] = input_proWeight.Text;
                d_dic["proMeter"] = input_proMeter.Text;
                d_dic["printNumer"] = input_printNumber.Text;
                d_dic["barType"] = "SC";
                d_dic["hDate"] = DateTime.Now.ToString("yyyy-MM-dd");
                d_dic["createuser"] = datas["userCode"].ToString();
                d_dic["happenDate"] = input_happenDate.EditValue.ToString().Replace('/', '-');


                foreach (var k in datas)
                {
                    if (!d_dic.ContainsKey(k.Key))
                    {
                        d_dic[k.Key] = k.Value;
                    }
                }

                d_dic["proName"] = input_produce_proName.Text;  //最后一道工序此处显示成品，其余工序生产的存货显示为半成品

                // 组织相关条码的列表数据
                if (!GenerateRelativeBarCodesDictionary())
                {
                    this.button_print.Enabled = true;
                    return;
                }

                datas["pusersName"] = input_pusers.Text;
                // 重新赋值，将用户名改为代码
                d_dic["pusers"] = input_pusers.Text;

                if (datas["gxCode"].ToString().Contains("FH"))
                {
                    d_dic["cu_rghssj"] = nowTime;  //入固化室时间
                }
                try
                {
                    d_dic["machine"] = ((ItemSelector)select_machine.GetSelectedDataRow()).code;
                }
                catch (Exception ex)
                {
                    d_dic["machine"] = "";
                }

                var printerName = ((ItemSelector)select_printer.GetSelectedDataRow()).code;
                var templatePath = ((ItemSelector)select_template.GetSelectedDataRow()).code;//模板路径
                string url = CommonMethods.APIUrl() + "SaveBarCode";
                var info = http.HttpPost(url, JsonConvert.SerializeObject(d_dic));
                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.button_print.Enabled = true;
                    return;
                }

                // 添加机台工序方法

                string gm_url = CommonMethods.APIUrl() + "GongXuMachine";
                var gm_info = http.HttpPost(gm_url, JsonConvert.SerializeObject(d_dic));

                //

                var obj = JsonConvert.DeserializeObject<JObject>(info);
                if (bool.Parse(obj["result"].ToString()))
                {
                    // 额外添加 生产标准，材质
                    //datas["zhxbz"] = input_zhxbz.EditValue == null ? "" : input_zhxbz.EditValue.ToString();
                    //datas["cu_caizhi"] = input_cu_material.EditValue == null ? "" : input_zhxbz.EditValue.ToString();
                    datas["zhxbz"] = input_zhxbz.Text == null ? "" : input_zhxbz.Text.ToString();
                    datas["cu_caizhi"] = input_cu_material.Text == null ? "" : input_zhxbz.Text.ToString();
                    if (datas["unitName"].ToString() == "千克")
                    {
                        datas["number"] = input_proWeight.Text;
                    }
                    else
                    {
                        datas["number"] = input_proMeter.Text;
                    }

                    datas["proName"] = input_produce_proName.Text;  //最后一道工序此处显示成品，其余工序生产的存货显示为半成品

                    if (datas["gxCode"].ToString().Contains("FH"))
                    {
                        datas["cu_rghssj"] = nowTime;   //入固化室时间
                    }

                    var table = CommonMethods.CreatePrintTableByDictionary(datas, obj["data"].ToString());

                    if (!string.IsNullOrWhiteSpace(gyPrintData))
                    {
                        var json = JsonConvert.DeserializeObject<JObject>(gyPrintData);
                        foreach (var j in json)
                        {
                            if (!table.Columns.Contains(j.Key.ToString()))
                            {
                                table.Columns.Add(j.Key.ToString());
                            }
                        }
                        foreach (DataRow r in table.Rows)
                        {
                            r.BeginEdit();
                            foreach (var j in json)
                            {
                                r[j.Key.ToString()] = j.Value.ToString();
                            }
                            r.EndEdit();
                        }
                    }

                    new ComputerTask().StartPrintingTask(table, printerName, templatePath);
                    //重新加载已打印条码列表

                    LoadPrintedBarCodes();
                }
                else
                {
                    XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.button_print.Enabled = true;
                    return;
                }

                ////清空关联条码
                //relativeBars.Clear();
                //gridControl_relativeBarCodes.RefreshDataSource();

                #region 刷新关联码
                List<UsedBarCode> newRelaBar = new List<UsedBarCode>();
                foreach (var bar in relativeBars)
                {
                    newRelaBar.Add(bar);
                }

                relativeBars.Clear();
                foreach (var bars in newRelaBar)
                {
                    var relativeBar = new RemoteRequest().GetScannedBarCodeInfo(bars.barCode, datas["plCode"], datas["gxCode"]);

                    if (relativeBar == null || relativeBar.barCode == null)
                    {
                        continue;
                    }

                    // 检查，不允许有相同的关联条码
                    if (relativeBars.Where(r => r.barCode == relativeBar.barCode).Count() > 0)
                    {
                        continue;
                    }

                    relativeBars.Add(relativeBar);

                    gridControl_relativeBarCodes.DataSource = relativeBars;
                    gridControl_relativeBarCodes.RefreshDataSource();

                    EnableTwoColumnEditable();
                }
                #endregion

                this.button_print.Enabled = true;

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        bool GenerateRelativeBarCodesDictionary()
        {
            // 如果没有选过关联条码
            if (relativeBars == null || relativeBars.Count == 0)
            {
                XtraMessageBox.Show("请在文本框内，扫描关联条码");
                return false;
            }

            var listDic = new List<Dictionary<string, string>>();

            foreach (var bar in relativeBars)
            {
                //if (double.Parse(bar.used_weight) > double.Parse(bar.proWeight) || double.Parse(bar.used_meter) > double.Parse(bar.proMeter))
                //{
                //    XtraMessageBox.Show("关联条码重量或米数错误，错误条码：" + bar.barCode);
                //    return false;
                //}

                var dic = new Dictionary<string, string>();
                dic["barCode"] = bar.barCode;
                dic["useWeight"] = bar.used_weight;
                dic["useMeter"] = bar.used_meter;
                dic["proWeight"] = bar.proWeight;
                dic["proMeter"] = bar.proMeter;
                dic["proCode"] = bar.proCode;

                listDic.Add(dic);
            }

            d_dic["relationBar"] = listDic;

            // 计算平均单价，添加批号

            var cu_iUnitCost = 0.0m;
            var cu_batch = "";

            foreach (var bar in relativeBars)
            {
                // 防止bar.cu_iUnitCost为空或者是非数字字符
                var tempUnitCost = 0.0m;
                decimal.TryParse(bar.cu_iUnitCost, out tempUnitCost);
                cu_iUnitCost += tempUnitCost;

                cu_batch += bar.cu_batch;
                cu_batch += ",";
            }

            cu_batch = cu_batch.TrimEnd(',');

            cu_iUnitCost = cu_iUnitCost / relativeBars.Count;

            datas["cu_iUnitCost"] = cu_iUnitCost.ToString();
            //datas["cu_batch"] = cu_batch;

            return true;
        }

        // 打印之前，检查必填项
        private bool CheckBeforePrint()
        {
            var result = false;

            //单位是米，并且米数为空（不一定是米，米数存的是非重量的单位）
            if (la_unitName.Text != "千克" && (string.IsNullOrEmpty(input_proMeter.Text) || decimal.Parse(input_proMeter.Text) == 0.0m))
            {
                XtraMessageBox.Show("请输入有效实际数量（米数/个数等）");
                return result;
            }

            if (string.IsNullOrEmpty(input_produce_proName.EditValue.ToString()) || input_produce_proName.EditValue.ToString() == "[请选择生产存货]")
            {
                XtraMessageBox.Show("请选择生产存货");
                return result;
            }
            if (input_cu_material.EditValue == null || string.IsNullOrEmpty(input_cu_material.EditValue.ToString()))
            {
                XtraMessageBox.Show("请填写材质");
                return false;
            }
            if (input_cu_batch.EditValue == null || string.IsNullOrEmpty(input_cu_batch.EditValue.ToString()))
            {
                XtraMessageBox.Show("请填写批号");
                return false;
            }
            //if (string.IsNullOrEmpty(input_pusers.EditValue.ToString()) || input_pusers.EditValue.ToString() == "[请选择生产人员]")
            //{
            //    XtraMessageBox.Show("请选择生产人员");
            //    return result;
            //}
            if (string.IsNullOrEmpty(input_pusers.Text.ToString()))
            {
                XtraMessageBox.Show("请填写生产人员");
                return result;
            }
            if (cb_isCheck.SelectedValue == "1" && (string.IsNullOrEmpty(input_cu_inspector.EditValue.ToString()) || input_cu_inspector.EditValue.ToString() == "[请选择检验人员]"))
            {
                XtraMessageBox.Show("请选择检验人员");
                return result;
            }
            if (select_printer.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印机");
                return result;
            }
            if (select_template.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印模板");
                return result;
            }

            foreach (var data in relativeBars)
            {
                if (string.IsNullOrEmpty(data.used_meter) || string.IsNullOrEmpty(data.used_weight))
                {
                    XtraMessageBox.Show("请填写关联条码使用米数和重量");
                    return result;
                }

                // 使用米数和重量，不能大于原条码米数和重量
                var check_used_meter = 0.0m;
                var check_used_weight = 0.0m;

                var check_ori_meter = 0.0m;
                var check_ori_weight = 0.0m;

                decimal.TryParse(data.used_meter, out check_used_meter);
                decimal.TryParse(data.used_weight, out check_used_weight);

                decimal.TryParse(data.proMeter, out check_ori_meter);
                decimal.TryParse(data.proWeight, out check_ori_weight);

                if (check_used_meter > check_ori_meter)
                {
                    XtraMessageBox.Show("使用米数不得大于关联条码原米数");
                    return result;
                }

                if (check_used_weight > check_ori_weight)
                {
                    XtraMessageBox.Show("使用重量不得大于关联条码原重量");
                    return result;
                }
            }

            result = true;
            return result;
        }


        private void button_exit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void button_complete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var diaResult = XtraMessageBox.Show("确认提交完工？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (diaResult != DialogResult.OK)
            {
                return;
            }

            var dic = new Dictionary<string, string>();
            dic["userCode"] = datas["userCode"].ToString();
            dic["plCode"] = datas["plCode"].ToString();
            dic["gxCode"] = datas["gxCode"].ToString();
            string url = CommonMethods.APIUrl() + "FinishPlan";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(dic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                XtraMessageBox.Show("生产结束了", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void input_proWeight_EditValueChanged(object sender, EventArgs e)
        {
            led_weight.Value = input_proWeight.EditValue.ToString();
        }

        private void btn_update_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var r = XtraMessageBox.Show("即将关闭程序进行升级，是否继续？", "提示", MessageBoxButtons.OKCancel);
            if (r == DialogResult.OK)
            {
                new RemoteRequest().UpdateCmdProgram();
            }
        }


        //UserSelectItem selectedUser;
        //private void input_pusers_Click(object sender, EventArgs e)
        //{
        //    var win = new UserSelector(datas["gxCode"]);

        //    win.ShowDialog();

        //    if (win.DialogResult == DialogResult.OK)
        //    {
        //        datas["pusers"] = win.selectedUser.userCode;
        //        //datas["userName"] = win.selectedUser.userName;

        //        input_pusers.EditValue = win.selectedUser.userName;

        //        selectedUser = new UserSelectItem
        //        {
        //            userCode = win.selectedUser.userCode,
        //            userName = win.selectedUser.userName,
        //        };

        //    }
        //}

        private void input_produce_proName_Click(object sender, EventArgs e)
        {
            var win = new ProductSelector();
            win.ShowDialog();

            if (win.DialogResult == DialogResult.OK)
            {
                datas["proCode"] = win.selectedProduct.proCode;
                datas["proName"] = win.selectedProduct.proName;
                datas["spec"] = win.selectedProduct.spec;
                datas["unitName"] = win.selectedProduct.proUnit;

                input_produce_proName.EditValue = win.selectedProduct.proName;
            }
        }

        UserSelectItem inspectorUser;

        private void input_cu_inspector_Click(object sender, EventArgs e)
        {
            // 检验人员也是该工序里的吗？是否有单独的检验工序？
            var win = new UserSelector(datas["gxCode"]);

            win.ShowDialog();

            if (win.DialogResult == DialogResult.OK)
            {
                datas["cu_inspector"] = win.selectedUser.userCode;
                //datas["userName"] = win.selectedUser.userName;

                input_cu_inspector.EditValue = win.selectedUser.userName;

                inspectorUser = new UserSelectItem
                {
                    userCode = win.selectedUser.userCode,
                    userName = win.selectedUser.userName,
                };
            }

        }

        List<UsedBarCode> relativeBars = new List<UsedBarCode>();
        private void input_relationBar_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var barCode = input_relationBar.EditValue.ToString();
                input_relationBar.EditValue = "";

                var relativeBar = new RemoteRequest().GetScannedBarCodeInfo(barCode, datas["plCode"], datas["gxCode"]);

                if (relativeBar == null || relativeBar.barCode == null)
                {
                    var args = new XtraMessageBoxArgs();
                    args.AutoCloseOptions.Delay = 2000;
                    args.AutoCloseOptions.ShowTimerOnDefaultButton = true;
                    args.Caption = "提示";
                    args.Text = "找不到该条码，请检查是否在车间库并标记占用";
                    XtraMessageBox.Show(args);
                    return;
                }

                // 检查，不允许有相同的关联条码
                if (relativeBars.Where(r => r.barCode == relativeBar.barCode).Count() > 0)
                {
                    return;
                }

                relativeBars.Add(relativeBar);

                gridControl_relativeBarCodes.DataSource = relativeBars;
                gridControl_relativeBarCodes.RefreshDataSource();

                EnableTwoColumnEditable();
            }
        }

        void EnableTwoColumnEditable()
        {
            foreach (GridColumn col in gridView_relativeBarCodes.Columns)
            {
                if (col.FieldName == "used_meter" || col.FieldName == "used_weight")
                {
                    col.OptionsColumn.ReadOnly = false;
                }
                else
                {
                    col.OptionsColumn.ReadOnly = true;
                }
            }
        }

        private void btn_clearRelative_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var selectedIndexes = gridView_relativeBarCodes.GetSelectedRows();
            if (selectedIndexes != null && selectedIndexes.Length == 1)
            {
                relativeBars.RemoveAt(selectedIndexes[0]);
                gridControl_relativeBarCodes.RefreshDataSource();
            }
        }

        private void btn_clearRelative_ItemDoubleClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            relativeBars.Clear();
            gridControl_relativeBarCodes.RefreshDataSource();
        }

        private void switch_com_Toggled(object sender, EventArgs e)
        {
            if (switch_com.IsOn)
            {
                OpenPort();
            }
            else
            {

            }
        }

        private void Form_SizeChanged(object sender, EventArgs e)
        {
            //AutoSizeFormClass asc = new AutoSizeFormClass();
            //asc.controlAutoSize(this);

        }

    }
}